
package com.kugou.game.sdk.ui.activity;

import com.kugou.framework.utils.UrlEncodeUtil;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.GameManager;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnRequestGameInfoListener;
import com.kugou.game.sdk.ui.widget.TipsLayout;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;

/**
 * 描述:游戏论坛界面
 * 
 * @author ljc
 * @since 2014年4月14日 下午5:11:16
 */
public class GameForumActivity extends BaseCommonTitleFragmentActivity {

    private final int MSG_BACK_REQUEST_GAME_INFO = 1;

    private final int MSG_UI_REQUEST_START = 2;

    private final int MSG_UI_REQUEST_GAME_INFO_SUCCESS = 3;

    private final int MSG_UI_REQUEST_GAME_INFO_FAILED = 4;

    private WebView wvGameForum;

    private TipsLayout mTipsLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = Rx.layout.kg_activity_game_forum;
        if (layoutId != 0) {
            setContentView(layoutId);
            // 设置标题
            setCommonTitle(Rx.string.kg_game_forum);
            // 设置View界面
            initViews();
        } else {
            showToast(Rx.string.kg_layout_not_found);
        }
        sendEmptyBackgroundMessage(MSG_BACK_REQUEST_GAME_INFO);
    }

    private void initViews() {
        wvGameForum = (WebView) findViewById(Rx.id.kg_wv_game_forum);
        wvGameForum.setVerticalScrollBarEnabled(false);
        WebSettings set = wvGameForum.getSettings();
        set.setJavaScriptEnabled(true);
        set.setDefaultTextEncodingName("utf-8");
        set.setCacheMode(WebSettings.LOAD_NO_CACHE);
        set.setUseWideViewPort(true);
        set.setLoadWithOverviewMode(false);
        wvGameForum.clearCache(true);
        wvGameForum.setWebViewClient(new AppWebViewClient());
        wvGameForum.setWebChromeClient(new AppWebChromeClient());
        // 添加js调用接口
        wvGameForum.addJavascriptInterface(new AndroidMethodProvider(), "KgSdkOperator");
        mTipsLayout = (TipsLayout) findViewById(Rx.id.kg_tips_layout);
        mTipsLayout.setLoadingText("");
        mTipsLayout.setLoadingViewBackground(Rx.drawable.kg_gamecenter_loading);
        mTipsLayout.setOnRefreshButtonClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sendEmptyBackgroundMessage(MSG_BACK_REQUEST_GAME_INFO);
            }
        });
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_REQUEST_GAME_INFO:
                sendEmptyUiMessage(MSG_UI_REQUEST_START);
                // 请求游戏信息，主要是获取论坛网址
                requestGameInfo();
                break;

            default:
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_UI_REQUEST_START:
                showLoadingLayout();
                break;
            case MSG_UI_REQUEST_GAME_INFO_SUCCESS:
                if (msg.obj != null) {
                    String url = msg.obj.toString();
                    refreshWebView(url);
                }
                break;
            case MSG_UI_REQUEST_GAME_INFO_FAILED:
                if (msg.obj != null && msg.obj instanceof String) {
                    String errorMsg = (String) msg.obj;
                    if (!TextUtils.isEmpty(errorMsg)) {
                        // tvResult.setText(errorMsg);
                    }
                }
                showResultLayout();
                break;
            default:
                break;
        }
    }

    /**
     * 获取到论坛网址后，更新webview的内容
     * 
     * @param appInfo
     */
    private void refreshWebView(String urlInfo) {
        wvGameForum.loadUrl(getUrl(urlInfo));
    }

    OnRequestGameInfoListener onRequestGameInfoListener = new OnRequestGameInfoListener() {

        @Override
        public void onSuccess(String url) {
            Message msg = new Message();
            msg.what = MSG_UI_REQUEST_GAME_INFO_SUCCESS;
            msg.obj = url;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg) {
            Message msg = new Message();
            msg.what = MSG_UI_REQUEST_GAME_INFO_FAILED;
            msg.obj = errorMsg;
            sendUiMessage(msg);
        }
    };

    /**
     * 请求游戏详情，主要获取论坛地址
     */
    private void requestGameInfo() {
        GameManager.requestGameInfo(onRequestGameInfoListener);

    }

    private void showLoadingLayout() {
        mTipsLayout.setVisibility(View.VISIBLE);
        mTipsLayout.show(TipsLayout.TYPE_LOADING);
        wvGameForum.setVisibility(View.GONE);
    }

    private void showWebView() {
        mTipsLayout.setVisibility(View.GONE);
        wvGameForum.setVisibility(View.VISIBLE);
    }

    private void showResultLayout() {
        wvGameForum.setVisibility(View.GONE);
        mTipsLayout.setVisibility(View.VISIBLE);
        mTipsLayout.show(TipsLayout.TYPE_FAILE);
    }

    private String getUrl(String forumUrl) {
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user == null) {
            return forumUrl;
        }
        String userName = user.getAccountName();
        String password = user.getPassword();
        String psw = "";
        if (!TextUtils.isEmpty(password)) {
            psw = AppUtil.getRASEncryptForForum(password);
        }
        String sign = AppUtil.getMd5StrForForum(userName, psw);
        if (!TextUtils.isEmpty(psw)) {
            psw = UrlEncodeUtil.encode(psw, "utf-8");
        }
        StringBuilder sb = new StringBuilder();
        sb.append(forumUrl).append("&").append("sdk_username=")
                .append(userName == null ? "" : userName).append("&").append("sdk_password=")
                .append(psw == null ? "" : psw).append("&").append("sdk_sign=")
                .append(sign == null ? "" : sign).append("&sdk_plat=1");
        return sb.toString();
    }

    class AppWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            showWebView();
        }
    }

    class AppWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            Builder builder = new Builder(view.getContext());
            builder.setTitle("提示");
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    });
            builder.show();
            return true;
        }

    }

    // 向网页提供的接口写在这里
    class AndroidMethodProvider {
        @JavascriptInterface
        public String getCurrentUser() {
            User user = UserManager.getInstance().getCurrentUserInternal();
            if (user == null) {
                return "";
            }
            String userName = user.getAccountName();
            String password = user.getPassword();
            String psw = "";
            if (!TextUtils.isEmpty(password)) {
                psw = AppUtil.getRASEncryptForForum(password);
            }
            String sign = AppUtil.getMd5StrForForum(userName, psw);
            HashMap<String, Object> hash = new HashMap<String, Object>();
            hash.put("username", userName == null ? "" : userName);
            hash.put("password", psw == null ? "" : psw);
            hash.put("sign", sign == null ? "" : sign);
            hash.put("plat", 1);
            return AppUtil.convertHashMapToJson(hash).replace("\\", "");
        }
    }

    @Override
    protected void onBackBtnClick() {
        if (wvGameForum.canGoBack()) {
            wvGameForum.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onBackPressed() {
        onBackBtnClick();
    }

}
